import { defineStore } from 'pinia'
import { ref } from 'vue'
import request from '@/api/request'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)
  const isLoggedIn = ref(!!token.value)

  // 设置token到localStorage
  const setToken = (newToken) => {
    token.value = newToken
    if (newToken) {
      localStorage.setItem('token', newToken)
      isLoggedIn.value = true
    } else {
      localStorage.removeItem('token')
      isLoggedIn.value = false
    }
  }

  // 登录
  const login = async (username, password) => {
    try {
      const response = await request.post('/auth/login', {
        username,
        password
      })

      if (response.success) {
        setToken(response.token)
        userInfo.value = response.user
        return { success: true }
      } else {
        return {
          success: false,
          message: response.message || '登录失败'
        }
      }
    } catch (error) {
      console.error('登录失败:', error)
      return {
        success: false,
        message: error.response?.data?.message || '登录失败'
      }
    }
  }

  // 获取当前用户信息
  const getUserInfo = async () => {
    try {
      const response = await request.get('/auth/me')
      if (response.success) {
        userInfo.value = response.user
        return true
      }
      return false
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // token失效，清除登录状态
      if (error.response?.status === 401) {
        logout()
      }
      return false
    }
  }

  // 登出
  const logout = () => {
    setToken('')
    userInfo.value = null
    isLoggedIn.value = false
  }

  // 修改密码
  const changePassword = async (oldPassword, newPassword) => {
    try {
      const response = await request.post('/auth/change-password', {
        oldPassword,
        newPassword
      })
      return response
    } catch (error) {
      console.error('修改密码失败:', error)
      return {
        success: false,
        message: error.response?.data?.message || '修改密码失败'
      }
    }
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    getUserInfo,
    logout,
    changePassword
  }
})

